/*
 * reader.go
 * 
 * Copyright 2013 Mykola Dvornik <mykola.dvornik@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * 
 */

package io

import (
	"fmt"
	"os"
	"code.google.com/p/semargl4/dump"
	. "code.google.com/p/semargl4/logger"
)

func Gather(filename string, cin chan In, cout chan Out, addr int64) {
	file, err := os.OpenFile(filename, os.O_RDONLY, 0666)
	defer file.Close()
	checkErr(err)
	r := dump.NewReader(file)
	r.GetHeaderOffset()
	Print(filename + " @ " + fmt.Sprintf("%d", r.HeaderOffset))
	myaddr := addr
	ok := true
	for ok {
		comm := <-cin
		// Just in case
		if comm.Mode == -1 {
			ok = false
			continue
		}
		if comm.Mode != 0 {
			continue
		}
		if comm.Addr != myaddr {
			continue
		}
		////////////////
		err := r.ReadAllToBuff(comm.Buf)
		result := Out{err, myaddr}
		cout <- result
	}
	cout <- Out{}
	Print("Close: " + filename)
}
